package com.xzt.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzt.bookstore.dto.UserInfoDTO;
import com.xzt.bookstore.entity.Blacklist;
import com.xzt.bookstore.entity.User;
import com.xzt.bookstore.mapper.BlacklistMapper;
import com.xzt.bookstore.service.UserInfoService;
import com.xzt.bookstore.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息服务实现类
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<BlacklistMapper, Blacklist> implements UserInfoService {
    
    private final UserService userService;
    
    public UserInfoServiceImpl(UserService userService) {
        this.userService = userService;
    }
    
    @Override
    public UserInfoDTO getUserInfo(Long userId) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return convertToDTO(user);
    }
    
    @Override
    public List<UserInfoDTO> searchUsersByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        
        // 使用MyBatis-Plus的模糊查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getUsername, username)
               .orderByDesc(User::getCreateTime);
        
        List<User> users = userService.list(wrapper);
        return users.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public Blacklist blockUser(Long userId, Long blockedUserId) {
        // 不能拉黑自己
        if (userId.equals(blockedUserId)) {
            throw new RuntimeException("不能拉黑自己");
        }
        
        // 检查被拉黑的用户是否存在
        User blockedUser = userService.getById(blockedUserId);
        if (blockedUser == null) {
            throw new RuntimeException("被拉黑的用户不存在");
        }
        
        // 检查是否已经拉黑
        LambdaQueryWrapper<Blacklist> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Blacklist::getUserId, userId)
               .eq(Blacklist::getBlockedUserId, blockedUserId);
        Blacklist existing = this.getOne(wrapper);
        
        if (existing != null) {
            throw new RuntimeException("该用户已在黑名单中");
        }
        
        // 创建黑名单记录
        Blacklist blacklist = new Blacklist();
        blacklist.setUserId(userId);
        blacklist.setBlockedUserId(blockedUserId);
        this.save(blacklist);
        
        return blacklist;
    }
    
    @Override
    public void unblockUser(Long userId, Long blockedUserId) {
        LambdaQueryWrapper<Blacklist> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Blacklist::getUserId, userId)
               .eq(Blacklist::getBlockedUserId, blockedUserId);
        
        Blacklist blacklist = this.getOne(wrapper);
        if (blacklist == null) {
            throw new RuntimeException("该用户不在黑名单中");
        }
        
        this.removeById(blacklist.getId());
    }
    
    @Override
    public List<UserInfoDTO> getBlacklist(Long userId) {
        LambdaQueryWrapper<Blacklist> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Blacklist::getUserId, userId)
               .orderByDesc(Blacklist::getCreateTime);
        
        List<Blacklist> blacklists = this.list(wrapper);
        
        return blacklists.stream()
                .map(blacklist -> {
                    User user = userService.getById(blacklist.getBlockedUserId());
                    return user != null ? convertToDTO(user) : null;
                })
                .filter(user -> user != null)
                .collect(Collectors.toList());
    }
    
    @Override
    public boolean isBlocked(Long userId, Long blockedUserId) {
        LambdaQueryWrapper<Blacklist> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Blacklist::getUserId, userId)
               .eq(Blacklist::getBlockedUserId, blockedUserId);
        
        return this.count(wrapper) > 0;
    }
    
    /**
     * 转换为DTO
     */
    private UserInfoDTO convertToDTO(User user) {
        UserInfoDTO dto = new UserInfoDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        dto.setPhone(user.getPhone());
        dto.setNickname(user.getNickname());
        dto.setAvatar(user.getAvatar());
        dto.setStatus(user.getStatus());
        dto.setCreateTime(user.getCreateTime());
        return dto;
    }
}

